<template>
  <view class="container">
    <!-- 头部 -->
    <view class="header">
      <text class="title">添加分类</text>
    </view>

    <!-- 表单内容 -->
    <view class="form">
      <view class="form-item">
        <text class="label">分类名称</text>
        <input 
          v-model="formData.name" 
          class="input" 
          placeholder="请输入分类名称"
          maxlength="50"
        />
        <text class="char-count">{{ formData.name?.length || 0 }}/50</text>
      </view>

      <view class="form-item">
        <text class="label">分类描述</text>
        <textarea 
          v-model="formData.description" 
          class="textarea" 
          placeholder="请输入分类描述"
          maxlength="200"
        />
        <text class="char-count">{{ formData.description?.length || 0 }}/200</text>
      </view>

      <view class="form-item">
        <text class="label">分类图片URL</text>
        <view class="url-input-group">
          <input 
            v-model="imageUrl" 
            class="input" 
            placeholder="请输入图片URL地址"
          />
          <button class="add-image-btn" @click="addImage">添加图片</button>
        </view>
        <text class="hint">建议使用网络图片URL，如：https://example.com/image.jpg</text>
        <view v-if="formData.image" class="image-preview">
          <image 
            :src="formData.image" 
            class="preview-image"
            mode="aspectFill"
            @error="handleImageError"
          />
          <text class="preview-url">{{ formData.image }}</text>
        </view>
      </view>

      <view class="form-row">
        <view class="form-item half">
          <text class="label">排序</text>
          <input 
            v-model="formData.sort" 
            class="input" 
            type="number"
            placeholder="0"
          />
          <text class="hint">数字越小越靠前</text>
        </view>

        <view class="form-item half">
          <text class="label">状态</text>
          <view class="radio-group">
            <label class="radio-item">
              <radio 
                value="1" 
                :checked="formData.status === 1"
                @click="formData.status = 1"
              />
              <text class="radio-text">启用</text>
            </label>
            <label class="radio-item">
              <radio 
                value="0" 
                :checked="formData.status === 0"
                @click="formData.status = 0"
              />
              <text class="radio-text">禁用</text>
            </label>
          </view>
        </view>
      </view>
    </view>

    <!-- 操作按钮 -->
    <view class="actions">
      <button class="btn cancel" @click="handleCancel">取消</button>
      <button class="btn submit" @click="handleSubmit">保存</button>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive } from 'vue'

// 响应式数据
const formData = reactive({
  name: '',
  description: '',
  image: '',
  sort: 0,
  status: 1
})

const loading = ref(false)
const imageUrl = ref('')

// 添加图片
const addImage = () => {
  if (!imageUrl.value || imageUrl.value.trim() === '') {
    uni.showToast({
      title: '请输入图片URL地址',
      icon: 'none'
    })
    return
  }
  
  // 简单的URL格式验证
  if (!imageUrl.value.startsWith('http://') && !imageUrl.value.startsWith('https://')) {
    uni.showToast({
      title: '请输入有效的URL地址（以http://或https://开头）',
      icon: 'none'
    })
    return
  }
  
  formData.image = imageUrl.value.trim()
  uni.showToast({
    title: '图片URL已添加',
    icon: 'success'
  })
}

// 图片加载错误处理
const handleImageError = () => {
  uni.showToast({
    title: '图片加载失败，请检查URL是否正确或是否存在防盗链',
    icon: 'none'
  })
}

// 取消操作
const handleCancel = () => {
  uni.navigateBack()
}

// 提交表单
const handleSubmit = async () => {
  // 表单验证
  if (!formData.name || formData.name.trim() === '') {
    uni.showToast({
      title: '分类名称不能为空',
      icon: 'none'
    })
    return
  }

  if (formData.name.trim().length > 50) {
    uni.showToast({
      title: '分类名称不能超过50个字符',
      icon: 'none'
    })
    return
  }

  if (formData.description && formData.description.length > 200) {
    uni.showToast({
      title: '分类描述不能超过200个字符',
      icon: 'none'
    })
    return
  }

  // 确保排序为数字
  formData.sort = parseInt(formData.sort) || 0
  if (formData.sort < 0) {
    uni.showToast({
      title: '排序值不能为负数',
      icon: 'none'
    })
    return
  }

  loading.value = true

  try {
    const result = await uniCloud.callFunction({
      name: 'food-categories',
      data: {
        action: 'add-category',
        data: {
          categoryData: {
            name: formData.name.trim(),
            description: formData.description || '',
            image: formData.image || '',
            sort: formData.sort,
            status: formData.status
          }
        }
      }
    })

    if (result.result.code === 200) {
      uni.showToast({
        title: '添加成功',
        icon: 'success'
      })
      
      // 延迟跳转到list页面
      setTimeout(() => {
        uni.redirectTo({
          url: '/pages/categories/list'
        })
      }, 500)
    } else {
      uni.showToast({
        title: result.result.message || '添加失败',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('添加分类失败:', error)
    uni.showToast({
      title: '网络错误，请重试',
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}
</script>

<style lang="scss" scoped>
.container {
  padding: 20rpx;
  min-height: 100vh;
  background-color: #f5f5f5;
}

.header {
  margin-bottom: 40rpx;
  
  .title {
    font-size: 36rpx;
    font-weight: bold;
    color: #333;
  }
}

.form {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 40rpx;
  margin-bottom: 40rpx;
}

.form-item {
  margin-bottom: 40rpx;
  position: relative;
  
  .label {
    display: block;
    font-size: 28rpx;
    color: #333;
    margin-bottom: 16rpx;
    font-weight: 500;
  }
  
  .input {
    width: 100%;
    height: 80rpx;
    border: 2rpx solid #e0e0e0;
    border-radius: 8rpx;
    padding: 0 24rpx;
    font-size: 28rpx;
    background-color: #fff;
    
    &:focus {
      border-color: #007aff;
    }
  }
  
  .textarea {
    width: 100%;
    height: 200rpx;
    border: 2rpx solid #e0e0e0;
    border-radius: 8rpx;
    padding: 24rpx;
    font-size: 28rpx;
    background-color: #fff;
    
    &:focus {
      border-color: #007aff;
    }
  }
  
  .char-count {
    position: absolute;
    right: 0;
    bottom: -40rpx;
    font-size: 24rpx;
    color: #999;
  }
  
  .hint {
    font-size: 24rpx;
    color: #999;
    margin-top: 8rpx;
  }
}

.form-row {
  display: flex;
  gap: 40rpx;
  
  .half {
    flex: 1;
  }
}

.url-input-group {
  display: flex;
  gap: 20rpx;
  align-items: center;
  
  .input {
    flex: 1;
  }
  
  .add-image-btn {
    background-color: #007aff;
    color: #fff;
    border: none;
    border-radius: 8rpx;
    padding: 0 32rpx;
    height: 80rpx;
    font-size: 28rpx;
    white-space: nowrap;
    
    &:active {
      background-color: #0056cc;
    }
  }
}

.image-preview {
  margin-top: 20rpx;
  border: 2rpx solid #e0e0e0;
  border-radius: 8rpx;
  padding: 20rpx;
  
  .preview-image {
    width: 200rpx;
    height: 200rpx;
    border-radius: 8rpx;
    margin-bottom: 16rpx;
  }
  
  .preview-url {
    display: block;
    font-size: 24rpx;
    color: #666;
    word-break: break-all;
  }
}

.radio-group {
  display: flex;
  gap: 40rpx;
  
  .radio-item {
    display: flex;
    align-items: center;
    gap: 12rpx;
    
    .radio-text {
      font-size: 28rpx;
      color: #333;
    }
  }
}

.actions {
  display: flex;
  gap: 20rpx;
  
  .btn {
    flex: 1;
    height: 88rpx;
    border-radius: 44rpx;
    font-size: 32rpx;
    border: none;
    
    &.cancel {
      background-color: #f0f0f0;
      color: #666;
      
      &:active {
        background-color: #e0e0e0;
      }
    }
    
    &.submit {
      background-color: #007aff;
      color: #fff;
      
      &:active {
        background-color: #0056cc;
      }
    }
  }
}
</style>